package com.lwt.kettle.common.config.kettle;


import com.lwt.kettle.common.utils.CommUtils;
import com.lwt.kettle.common.utils.SpringContextUtils;
import org.pentaho.di.cluster.SlaveServer;

import java.util.ArrayList;
import java.util.Random;


public class KettleServerFactory {
    private static Integer pos = 0;
    private static KettleConfig kettleConfig;

    static {
        if (CommUtils.isNull(kettleConfig)) {
            kettleConfig = (KettleConfig) SpringContextUtils.getBean(KettleConfig.class);
        }
    }

    public static SlaveServer createSlaveServer() {
        SlaveServer remoteSlaveServer = new SlaveServer();
        KettleConfig.Server server = getServerByRoundRobin();
        remoteSlaveServer.setHostname(server.getUrl());
        remoteSlaveServer.setUsername(server.getUsername());
        remoteSlaveServer.setPassword(server.getPwd());
        remoteSlaveServer.setPort(server.getPort());
        return remoteSlaveServer;
    }

    public static String getJobPath() {
        return kettleConfig.getJobPath();
    }

    public static String getPlanPath() {
        return kettleConfig.getPlanPath();
    }

    /**
     * 轮询获取 Round Robin
     *
     * @return
     */
    private static KettleConfig.Server getServerByRoundRobin() {
        KettleConfig.Server server = null;

        ArrayList<KettleConfig.Server> keyList = new ArrayList<>();
        keyList.addAll(kettleConfig.getServers());

        synchronized (pos) {
            if (pos >= kettleConfig.getServers().size()) {
                pos = 0;
            }
            server = keyList.get(pos);
            pos++;
        }
        return server;
    }

    /**
     * 随机获取 Random
     *
     * @return
     */
    private static KettleConfig.Server getServerByRandom() {
        KettleConfig.Server server = null;

        ArrayList<KettleConfig.Server> keyList = new ArrayList<>();
        keyList.addAll(kettleConfig.getServers());

        Random random = new Random();
        int randomPos = random.nextInt(keyList.size());
        server = keyList.get(randomPos);
        return server;
    }


}
